'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Users, Shield, Settings, LogOut, Home } from 'lucide-react'

interface User {
  id: number
  username: string
  email: string
  full_name: string
  role_code: string
  role_name: string
  permissions: {
    canEditAll: boolean
    canManageUsers: boolean
    canManageRoles: boolean
    dataSourceAccess: string[]
  }
}

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  const router = useRouter()

  useEffect(() => {
    checkAuth()
  }, [])

  const checkAuth = async () => {
    try {
      const response = await fetch('/api/auth/me')
      const data = await response.json()

      if (data.success) {
        setUser(data.data.user)
        // 检查是否有管理权限
        if (!data.data.user.permissions.canManageUsers && !data.data.user.permissions.canManageRoles) {
          router.push('/')
          return
        }
      } else {
        router.push('/login')
      }
    } catch (error) {
      console.error('认证检查失败:', error)
      router.push('/login')
    } finally {
      setLoading(false)
    }
  }

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', { method: 'POST' })
      router.push('/login')
    } catch (error) {
      console.error('登出失败:', error)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  if (!user) {
    return null
  }

  const menuItems = [
    {
      href: '/admin',
      icon: Settings,
      label: '管理概览',
      description: '系统管理概览'
    },
    {
      href: '/admin/users',
      icon: Users,
      label: '用户管理',
      description: '管理系统用户',
      permission: 'canManageUsers'
    },
    {
      href: '/admin/roles',
      icon: Shield,
      label: '角色管理',
      description: '管理用户角色和权限',
      permission: 'canManageRoles'
    }
  ]

  const availableMenuItems = menuItems.filter(item => 
    !item.permission || user.permissions[item.permission as keyof typeof user.permissions]
  )

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 顶部导航 */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <Link href="/" className="flex items-center space-x-2 text-blue-600 hover:text-blue-800">
                <Home className="h-5 w-5" />
                <span className="font-medium">返回首页</span>
              </Link>
              <div className="h-6 w-px bg-gray-300"></div>
              <h1 className="text-xl font-semibold text-gray-900">系统管理</h1>
            </div>
            
            <div className="flex items-center space-x-4">
              <div className="text-sm">
                <div className="font-medium text-gray-900">{user.full_name}</div>
                <div className="flex items-center space-x-2">
                  <Badge variant="secondary">{user.role_name}</Badge>
                  <span className="text-gray-500">({user.username})</span>
                </div>
              </div>
              <Button variant="outline" size="sm" onClick={handleLogout}>
                <LogOut className="h-4 w-4 mr-2" />
                登出
              </Button>
            </div>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* 侧边栏导航 */}
          <div className="lg:col-span-1">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">管理菜单</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {availableMenuItems.map((item) => {
                  const Icon = item.icon
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      className="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-100 transition-colors"
                    >
                      <Icon className="h-5 w-5 text-gray-600" />
                      <div>
                        <div className="font-medium text-gray-900">{item.label}</div>
                        <div className="text-sm text-gray-500">{item.description}</div>
                      </div>
                    </Link>
                  )
                })}
              </CardContent>
            </Card>

            {/* 权限信息 */}
            <Card className="mt-6">
              <CardHeader>
                <CardTitle className="text-lg">当前权限</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {user.permissions.canEditAll && (
                    <Badge variant="default">全部编辑权限</Badge>
                  )}
                  {user.permissions.canManageUsers && (
                    <Badge variant="secondary">用户管理</Badge>
                  )}
                  {user.permissions.canManageRoles && (
                    <Badge variant="secondary">角色管理</Badge>
                  )}
                  <div className="mt-3">
                    <div className="text-sm font-medium text-gray-700 mb-1">数据来源权限:</div>
                    <div className="flex flex-wrap gap-1">
                      {user.permissions.dataSourceAccess.map(source => (
                        <Badge key={source} variant="outline" className="text-xs">
                          {source === 'P' && '采购'}
                          {source === 'E' && '工程'}
                          {source === 'M' && '制造'}
                          {source === 'O' && '运维'}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 主内容区域 */}
          <div className="lg:col-span-3">
            {children}
          </div>
        </div>
      </div>
    </div>
  )
}
